package com.sailors.common.task.sdk.config.property;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;

@Component
@Slf4j
public class PropertyLoader {

    @Autowired
    private ResourceLoader resourceLoader;

    public JSONObject loadKafkaConfig(String env) {
        return JSON.parseObject(loadConfig(PropertyPath.KAFKA_PATH, env));
    }

    public String loadUrlConfig(String env) {
        return loadConfig(PropertyPath.URL_PATH, env);
    }

    private String loadConfig(String path, String env) {
        StringBuilder loadConfig = new StringBuilder();
        try {
            Resource resource = resourceLoader.getResource(path);
            InputStream inputStream = resource.getInputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) != -1) {
                loadConfig.append(new String(buf, 0, len));
            }
            inputStream.close();
        } catch (IOException e) {
            log.warn("load config failed!!!: {}", e.getMessage());
            return null;
        }

        if (StringUtils.isEmpty(loadConfig)) {
            return null;
        }
        JSONObject config = JSON.parseObject(loadConfig.toString());
        return config.containsKey(env) ? config.getString(env) : null;
    }
}

